package com.zbxx.practice.jdbcpool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * @date 2019/05/27
 */
public class ConnectionRunTest {

    static String sql = "insert into user (name,password) values(?,?)";


    /**
     * 这里线程池  总共指挥创建 十五个线程  是个核心线程 但是会缓存五个复用
     *
     * @param args
     */
    public static void main(String[] args) {
        DataSourcePool dataSourcePool = new DataSourcePool();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20,
                60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5));
        for (int i = 0; i < 20; i++) {
            threadPoolExecutor.execute(() -> {
                Connection connection = null;
                try {
                    connection = dataSourcePool.getConnection();
                    connection.setAutoCommit(false);
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, "account");
                    preparedStatement.setString(2, "account");
                    preparedStatement.executeUpdate();
                    connection.commit();
                    connection.close();
                } catch (Exception e) {
                    try {
                        connection.rollback();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                    System.out.println("数据插入失败 " + e.getMessage());
                }
            });
            System.out.println("线程池中现在的线程数目是：" + threadPoolExecutor.getPoolSize() + ",  队列中正在等待执行的任务数量为：" + threadPoolExecutor.getQueue().size());
        }

    }

}
